<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in artlish" :key="item.id" :label="item.cate_name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="search">筛选</el-button>
            <el-button type="info" size="small" @click="resetform">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="isartlist_show = true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artlishForm" style="width: 100%">
        <el-table-column prop="title" label="文章标题" width="120">
          <template v-slot="{ row }">
            <el-link type="info" @click="toshowrow(row)">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="分类" width="120"> </el-table-column>
        <el-table-column label="发布时间" width="120">
          <template v-slot="{ row }">
            {{ row.pub_data | totime }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="120"> </el-table-column>
        <!-- //1.添加作用域插槽,函数操作获取当前行数据,添加事件 -->
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="success" @click="todetele(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[1, 2]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 对话框发布区域 -->
    <el-dialog
      title="发布文章"
      :visible.sync="isartlist_show"
      :fullscreen="true"
      :before-close="handleClose"
      @closed="resetpublish"
    >
      <!-- <span>这是一段信息</span> -->
      <el-form :model="pubForm" :rules="pubFormRules" ref="publishRef" label-width="80px">
        <el-form-item prop="title" label="文章标题">
          <el-input placeholder="请输入标题" v-model="pubForm.title"></el-input>
        </el-form-item>
        <el-form-item prop="cate_id" label="文章分类">
          <el-select v-model="pubForm.cate_id" style="width: 100%" placeholder="请输入文章分类">
            <el-option v-for="item in artlish" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="content" label="文章内容">
          <quill-editor v-model="pubForm.content" placeholder="请输入文章内容"></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img v-if="img_URl" :src="img_URl" alt="" class="cover-img" ref="imgRef" />
          <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none" accept="image/*" ref="iptFileRef" @change="imgshow" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="imgadd">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="setstate(`已发布`)"> 发布文章</el-button>
          <el-button @click="setstate(`草稿`)">存稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ artDetail.pub_date | totime }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <!-- 文章的封面 -->
      <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

      <!-- 文章的详情 -->
      <div v-html="artDetail.content" class="detail-box"></div>
    </el-dialog>
  </div>
</template>

<script>
// 按需导入获取文章分类数据的接口
import { artAPI } from '@/api/cate.js'
// 按需导入获取,删除文章分类数据的接口
import { publishAPI, artlishAPI, artdelAPI, getartAPI } from '@/api/art.js'
export default {
  name: 'ArtList',
  data() {
    return {
      // data查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      artDetail: {
        nickname: '',
        username: '',
        pub_date: '',
        cate_name: '',
        state: ''
      },
      detailVisible: false,
      // data中定义获取文章分类数据对象
      artlishForm: [],
      // data中定义//data中定义总条数
      total: 1,
      isartlist_show: false,
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        state: '',
        cover_img: ''
      },
      pubFormRules: {
        title: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] },
          { pattern: /^.{1,30}$/, message: '要求1-30 个字符', trigger: ['change', 'blur'] }
        ],
        cate_id: [{ required: true, message: '不能为空', trigger: ['change', 'blur'] }],
        content: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] },
          { pattern: /^\S*$/, message: '不能为空字符', trigger: ['change', 'blur'] }
        ]
      },
      artlish: [],
      img_URl: ''
    }
  },
  created() {
    this.toartlish()
    // 5.已创建立刻调用
    this.art_toshow()
  },
  methods: {
    async handleClose(done) {
      const result = await this.$confirm('此操作发布该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result === 'cancel') {
        done(false)
      } else {
        done()
      }
    },
    async toartlish() {
      const { data: res } = await artAPI()
      if (res.code === 1) {
        this.$message.error(res.message)
      } else {
        this.artlish = res.data
      }
    },
    imgadd() {
      this.$refs.iptFileRef.click()
    },
    imgshow() {
      const files = this.$refs.iptFileRef.files
      console.dir(files)
      if (files.length === 0) return
      this.img_URl = URL.createObjectURL(files[0])
      this.pubForm.cover_img = files[0]
    },
    setstate(state) {
      this.pubForm.state = state
      this.$refs.publishRef.validate(async valid => {
        if (!valid) return
        if (!this.pubForm.content) return this.$message.error('文章内容不能为空')
        if (!this.pubForm.cover_img) return this.$message.error('文章封面不能为空')

        const fn = new FormData()
        for (const k in this.pubForm) {
          fn.append(k, this.pubForm[k])
        }
        const { data: res } = await publishAPI(fn)
        if (res.code === 1) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.isartlist_show = false
        this.art_toshow()
      })
    },
    resetpublish() {
      this.$refs.publishRef.resetFields()
      this.pubForm.cover_img = ''
      for (const k in this.pubForm) {
        this.pubForm[k] = ''
      }
      this.img_URl = ''
    },
    // 定义定义获取文章分类数据函数
    async art_toshow() {
      const { data: res } = await artlishAPI(this.q)
      console.log(res)
      if (res.code === 1) return this.$message.error(res.message)
      // 转存数据
      this.artlishForm = res.data
      // 转存条数
      this.total = res.total
    },
    // 4.事件处理函数中设置
    async todetele(n) {
      // 确定框-是否删除
      const result = await this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result === 'cancel') return this.$message.error('点击取消成功')
      // 确定取消后-执行axios请求
      // n:当前行数据
      const { data: res } = await artdelAPI(n.id)
      // 请求不成功-提示用户
      if (res.code === 1) return this.$message.error(res.message)
      // 请求成功-判断列表数组长度是否=1和页码值是否>1 // 页码值--
      if (this.artlishForm.length === 1 && this.q.pagenum > 1) {
        this.q.pagenum--
      }
      // 重新渲染页面执行 获取文章分类数据的函数
      this.art_toshow()
    },
    // 监听页面展示条数发生变化
    handleSizeChange(n) {
      // 形参为最新的条数
      this.q.pagesize = n
      // 默认让他显示第一条
      this.q.pagenum = 1
      // 重新渲染data数据
      this.art_toshow()
    },
    // 监听页码值发生变化
    handleCurrentChange(n) {
      // 形参为最新的页码值
      // 赋值给q
      this.q.pagenum = n
      // 重新渲染data数据
      this.art_toshow()
    },
    // 3.筛选1
    search() {
      // 第3.1步 页面一开始显示第一页-将data查询参数对象中页码值设为1
      // 第3.2步 重新执行获取文章分类数据的函数-this.函数()
      this.q.pagenum = 1
      this.art_toshow()
    },
    resetform() {
      this.q.pagenum = 1
      this.q.cate_id = ''
      this.q.state = ''

      this.art_toshow()
    },
    // 5.对应的点击处理事件函数中
    async toshowrow(n) {
      // n:点击的当前行数据
      // 执行ajax请求
      const { data: res } = await getartAPI(n.id)
      // 请求不成功--提示用户
      if (res === 1) return this.$message.error(res.message)
      // 转存到data vue变量中
      this.artDetail = res.data
      // 控制对话框显示
      this.detailVisible = true
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
